﻿using Microsoft.EntityFrameworkCore;
using SJ.Platform.Common;
using SJ.Platform.EFCore.Model;
using SJ.Platform.EFCore.Model.ApproveManager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace SJ.Platform.EFCore.DBOperation.DBOperation.MySQL.Approve
{
    public class Approve_RecordHandle
    {
        private readonly SJDBContext _context;

        public Approve_RecordHandle(SJDBContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> CreateAsync(List<ApproveRecord> entityList)
        {
            try
            {
                int result = 0;
                if (entityList != null && entityList.Count > 0)
                {
                    foreach (ApproveRecord entity in entityList)
                    {
                        _context.ApproveRecords.Add(entity);
                    }
                    result = await _context.SaveChangesAsync();
                }

                return result > 0;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Approve_RecordHandle=>Create", ex);
                return false;
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdateAsync(ApproveRecord entity)
        {
            try
            {
                _context.Entry(entity).State = EntityState.Modified;
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Approve_RecordHandle=>Update", ex);
                return false;
            }
        }

        /// <summary>
        /// 根据主流程ID更新审批结果
        /// </summary>
        /// <param name="pId"></param>
        /// <returns></returns>
        public async Task<bool> UpdateRecordsByPIdAsync(string pId)
        {
            try
            {
                var approves = await _context.ApproveRecords.Where(a => a.PId == pId).ToListAsync();
                int count = _context.Database.ExecuteSqlRaw($"update approve_record set IsCheck=1 where PId='{pId}';");
                return approves.Count == count;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Approve_RecordHandle=>DeleteByPIdAsync", ex);
            }
            return false;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Delete(ApproveRecord entity)
        {
            try
            {
                _context.ApproveRecords.Remove(entity);
                return _context.SaveChanges() > 0;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Approve_RecordHandle=>Delete", ex);
                return false;
            }
        }

        /// <summary>
        /// 根据主键删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DeleteByIdAsync(string id)
        {
            try
            {
                var entity = _context.ApproveRecords.Find(id);
                if (entity != null)
                {
                    _context.ApproveRecords.Remove(entity);
                    await _context.SaveChangesAsync();
                    return true;
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Approve_RecordHandle=>DeleteById", ex);
            }
            return false;
        }

        /// <summary>
        /// 根据主流程ID删除
        /// </summary>
        /// <param name="pId"></param>
        /// <returns></returns>
        public async Task<bool> DeleteByPIdAsync(string pId)
        {
            try
            {
                var approves = await _context.ApproveRecords.Where(a => a.PId == pId).ToListAsync();
                int count = _context.Database.ExecuteSqlRaw($"delete from approve_record where PId='{pId}';");
                return approves.Count == count;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Approve_RecordHandle=>DeleteByPIdAsync", ex);
            }
            return false;
        }

        /// <summary>
        /// 根据节点ID删除
        /// </summary>
        /// <param name="nodeId"></param>
        /// <returns></returns>
        public async Task<bool> DeleteByNodeIdAsync(string nodeId)
        {
            try
            {
                var approves = await _context.ApproveRecords.Where(a => a.NodeId == nodeId).ToListAsync();
                int count = _context.Database.ExecuteSqlRaw($"delete from approve_record where NodeId='{nodeId}';");
                return approves.Count == count;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Approve_RecordHandle=>DeleteByNodeIdAsync", ex);
            }
            return false;
        }

        /// <summary>
        /// 根据ID获取实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApproveRecord> GetEntityByIdAsync(string id)
        {
            try
            {
                return await _context.ApproveRecords.FindAsync(id);
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Approve_RecordHandle=>GetEntityById", ex);
            }
            return null;
        }


        /// <summary>
        /// 获取当前用户，当前流程的待审批信息
        /// </summary>
        /// <param name="approveUserId"></param>
        /// <param name="pId"></param>
        /// <returns></returns>
        public async Task<ApproveRecord> GetWaitToBeDownRecordAsync(string approveUserId, string pId)
        {
            try
            {
                var query = _context.ApproveRecords.AsQueryable();

                query = query.Where(r => r.ApproveUserId == approveUserId && r.PId == pId && r.IsCheck == 0);

                return await query.FirstAsync();
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Approve_RecordHandle=>GetWaitToBeDownRecordAsync ", ex);
            }
            return null;
        }

        /// <summary>
        /// 获取流程下所有已审核过的审批记录
        /// </summary>
        /// <param name="pId"></param>
        /// <returns></returns>
        public async Task<List<ApproveRecord>> GetAllCheckedRecordsByPIdAsync(string pId)
        {
            try
            {
                var query = _context.ApproveRecords.AsQueryable();

                query = query.Where(r => r.PId == pId && r.IsCheck == 1).OrderBy(r => r.ApproveTime);

                return await query.ToListAsync();
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Approve_RecordHandle=>GetAllCheckedRecordsByPIdAsync ", ex);
            }
            return null;
        }

        /// <summary>
        /// 获取流程下某个节点未审核过的审批记录
        /// </summary>
        /// <param name="pId"></param>
        /// <param name="nodeId"></param>
        /// <returns></returns>
        public async Task<List<ApproveRecord>> GetNoCheckRecordsByPIdAndNodeIdAsync(string pId, string nodeId)
        {
            try
            {
                var query = _context.ApproveRecords.AsQueryable();

                query = query.Where(r => r.PId == pId && r.NodeId == nodeId && r.IsCheck == 0);

                return await query.ToListAsync();
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Approve_RecordHandle=>GetNoCheckRecordsByPIdAndNodeIdAsync ", ex);
            }
            return null;
        }
    }
}
